<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.0.1">


  <link rel="mask-icon" href="/images/logo.svg?v=7.0.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.0.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="在前面我们已经知道在springboot中如何使用freemark与thymeleaf之类的视图模板引擎去渲染我们的视图页面，但是没涉及跟数据库交互的东西，所以今天在这里我们将介绍了一下如何在springboot中通过spring data jpa操作mysql数据库，并且构建一套简单的rest api接口。">
<meta name="keywords" content="SpringBoot,SpringDataJpa,Rest">
<meta property="og:type" content="article">
<meta property="og:title" content="【SpringBoot2.0系列04】SpringBoot之使用JPA完成简单的restapi">
<meta property="og:url" content="http://www.yukonga.cn/2018/08/17/【SpringBoot2-0系列04】SpringBoot之使用JPA完成简单的restapi/index.html">
<meta property="og:site_name" content="yukong&#39;s blog">
<meta property="og:description" content="在前面我们已经知道在springboot中如何使用freemark与thymeleaf之类的视图模板引擎去渲染我们的视图页面，但是没涉及跟数据库交互的东西，所以今天在这里我们将介绍了一下如何在springboot中通过spring data jpa操作mysql数据库，并且构建一套简单的rest api接口。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062037.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062003.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062049.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062103.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062116.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062128.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062138.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062146.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062154.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062202.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062211.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062219.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062227.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-055539.jpg">
<meta property="og:updated_time" content="2019-05-07T06:22:33.916Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【SpringBoot2.0系列04】SpringBoot之使用JPA完成简单的restapi">
<meta name="twitter:description" content="在前面我们已经知道在springboot中如何使用freemark与thymeleaf之类的视图模板引擎去渲染我们的视图页面，但是没涉及跟数据库交互的东西，所以今天在这里我们将介绍了一下如何在springboot中通过spring data jpa操作mysql数据库，并且构建一套简单的rest api接口。">
<meta name="twitter:image" content="http://cdn.yukonga.cn/2019-05-07-062037.jpg">



  <link rel="alternate" href="/atom.xml" title="yukong's blog" type="application/atom+xml">




  <link rel="canonical" href="http://www.yukonga.cn/2018/08/17/【SpringBoot2-0系列04】SpringBoot之使用JPA完成简单的restapi/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>【SpringBoot2.0系列04】SpringBoot之使用JPA完成简单的restapi | yukong's blog</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?45b7a3cfe46b3fa2c5d46f59f590664e";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">yukong's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">learning program</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.yukonga.cn/2018/08/17/【SpringBoot2-0系列04】SpringBoot之使用JPA完成简单的restapi/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yukong">
      <meta itemprop="description" content="你若对得起时间，时间便对得起你">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="yukong's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【SpringBoot2.0系列04】SpringBoot之使用JPA完成简单的restapi

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-08-17 11:59:28" itemprop="dateCreated datePublished" datetime="2018-08-17T11:59:28+08:00">2018-08-17</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-05-07 14:22:33" itemprop="dateModified" datetime="2019-05-07T14:22:33+08:00">2019-05-07</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/SpringBoot/" itemprop="url" rel="index"><span itemprop="name">SpringBoot</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/2018/08/17/【SpringBoot2-0系列04】SpringBoot之使用JPA完成简单的restapi/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2018/08/17/【SpringBoot2-0系列04】SpringBoot之使用JPA完成简单的restapi/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
            <span id="/2018/08/17/【SpringBoot2-0系列04】SpringBoot之使用JPA完成简单的restapi/" class="leancloud_visitors" data-flag-title="【SpringBoot2.0系列04】SpringBoot之使用JPA完成简单的restapi">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在前面我们已经知道在springboot中如何使用<code>freemark</code>与<code>thymeleaf</code>之类的视图模板引擎去渲染我们的视图页面，但是没涉及跟数据库交互的东西，所以今天在这里我们将介绍了一下如何在<code>springboot</code>中通过<code>spring data jpa</code>操作<code>mysql</code>数据库，并且构建一套简单的<code>rest api</code>接口。</p>
<a id="more"></a>
<h1 id="一-前言"><a class="markdownIt-Anchor" href="#一-前言"></a> 一、前言</h1>
<h2 id="11-spring-data-jpa-介绍"><a class="markdownIt-Anchor" href="#11-spring-data-jpa-介绍"></a> 1.1、Spring Data Jpa 介绍</h2>
<p>Spring Data JPA是Spring基于Hibernate开发的一个JPA框架。如果用过Hibernate或者MyBatis的话，就会知道对象关系映射（ORM）框架有多么方便。但是Spring Data JPA框架功能更进一步，为我们做了 一个数据持久层框架几乎能做的任何事情。并且提供了基础的增删改查方法，具体api请看<a href="https://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/" target="_blank" rel="noopener">官网</a>。</p>
<h2 id="22"><a class="markdownIt-Anchor" href="#22"></a> 2.2</h2>
<p>REST是所有Web应用都应该遵守的架构设计指导原则。<br>
Representational State Transfer，翻译是”表现层状态转化”。<br>
面向资源是REST最明显的特征，对于同一个资源的一组不同的操作。资源是服务器上一个可命名的抽象概念，资源是以名词为核心来组织的，首先关注的是名词。REST要求，必须通过统一的接口来对资源执行各种操作。对于每个资源只能执行一组有限的操作。（7个HTTP方法：GET/POST/PUT/DELETE/PATCH/HEAD/OPTIONS）<br>
关于<code>rest api</code>如何涉及我也是从<a href="http://www.ruanyifeng.com/blog/2014/05/restful_api.html" target="_blank" rel="noopener">阮一峰</a>老师那里学习的。</p>
<h1 id="二-目标"><a class="markdownIt-Anchor" href="#二-目标"></a> 二、目标</h1>
<p>首先我们有一个<code>user</code>表，我们希望能通过构建出对应的<code>rest api</code>对表中的数据完成增删改查操作。<br>
jpa的依赖如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">    &lt;dependency&gt;</span><br><span class="line">        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;</span><br><span class="line">    &lt;/dependency&gt;</span><br><span class="line"></span><br><span class="line">    &lt;dependency&gt;</span><br><span class="line">        &lt;groupId&gt;mysql&lt;/groupId&gt;</span><br><span class="line">        &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;</span><br><span class="line">        &lt;scope&gt;runtime&lt;/scope&gt;</span><br><span class="line">    &lt;/dependency&gt;</span><br><span class="line">    &lt;dependency&gt;</span><br><span class="line">        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">        &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;</span><br><span class="line">        &lt;scope&gt;test&lt;/scope&gt;</span><br><span class="line">    &lt;/dependency&gt;</span><br><span class="line">    &lt;dependency&gt;</span><br><span class="line">        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">        &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;</span><br><span class="line">    &lt;/dependency&gt;</span><br><span class="line">&lt;/dependencies&gt;</span><br></pre></td></tr></table></figure>
<p>接下来那么第一步就是创表了<br>
1、创表<br>
由于我们使用的spring data  jpa 而jpa的底层实现是hibernate，用过hibernate的同学知道 hibernate可以通过实体类逆向创建表，只需要配置一下<code>ddl-auto</code> 就可以<br>
所以我们需要在<code>application.yml</code>配置一下</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">server:</span></span><br><span class="line"><span class="attr">  port:</span> <span class="number">8989</span></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line"><span class="attr">  datasource:</span></span><br><span class="line"><span class="attr">    username:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">    password:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">    url:</span> <span class="attr">jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf8</span></span><br><span class="line"><span class="attr">    driver-class-name:</span> <span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">  jpa:</span></span><br><span class="line"><span class="attr">    hibernate:</span></span><br><span class="line"><span class="attr">      ddl-auto:</span> <span class="string">update</span></span><br><span class="line"><span class="attr">    show-sql:</span> <span class="literal">true</span></span><br></pre></td></tr></table></figure>
<p>在上面的配置文件中 我们配置了一个数据源跟tomcat端口还有jpa的配置。其中 <code>show-sql: true</code> 代表会在日志中打印我们操作的sql、<br>
而另外 <code>ddl-auto</code>有四个值可选，分别是</p>
<ul>
<li><code>create</code> 启动时删数据库中的表，然后创建，退出时不删除数据表</li>
<li><code>create-drop</code> 启动时删数据库中的表，然后创建，退出时删除数据表 如果表不存在报错</li>
<li><code>update</code> 最常用的属性，第一次加载hibernate时根据model类会自动建立起表的结构（前提是先建立好数据库），以后加载hibernate时根据 model类自动更新表结构，即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后，表结构是不会被马上建立起来的，是要等 应用第一次运行起来后才会。</li>
<li><code>validate</code> 项目启动表结构进行校验 如果不一致则报错</li>
</ul>
<hr>
<p>所以这里我们希望当表创建成功后  下次启动数据还在我们就选择了<code>update</code>模式，其次我们需要在本地的<code>mysql</code>数据库新建一个<code>test</code>数据库。<br>
接下来我们需要编写的我们实体类<code>User.java</code>了 <code>hibernate</code>将会通过实体类的结构在<code>test</code>数据库中创建一个对应的<code>user</code>表<br>
新建包<code>entity</code> 创建<code>User.java</code>代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@JsonIgnoreProperties</span>(value=&#123;<span class="string">"hibernateLazyInitializer"</span>,<span class="string">"handler"</span>,<span class="string">"fieldHandler"</span>&#125;) </span><br><span class="line"><span class="meta">@Entity</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Id</span></span><br><span class="line">    <span class="meta">@GeneratedValue</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 用户名</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Column</span>(name = <span class="string">"username"</span>, nullable = <span class="keyword">true</span>, length = <span class="number">32</span>)</span><br><span class="line">    <span class="keyword">private</span> String username;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 密码</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Column</span>(name = <span class="string">"password"</span>, nullable = <span class="keyword">true</span>, length = <span class="number">32</span>)</span><br><span class="line">    <span class="keyword">private</span> String password;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 年龄</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Column</span>(name = <span class="string">"age"</span>, nullable = <span class="keyword">true</span>, length = <span class="number">11</span>)</span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 性别 1=男 2=女 其他=保密</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Column</span>(name = <span class="string">"sex"</span>, nullable = <span class="keyword">true</span>, length = <span class="number">11</span>)</span><br><span class="line">    <span class="keyword">private</span> Integer sex;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getUsername</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setUsername</span><span class="params">(String username)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.username = username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getPassword</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPassword</span><span class="params">(String password)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.password = password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">getAge</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAge</span><span class="params">(Integer age)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.age = age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">getSex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> sex;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setSex</span><span class="params">(Integer sex)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.sex = sex;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">getId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>至此，我们的user表也算是创建好了，当我们的程序第一个启动的时候<code>jpa</code>会自动在<code>test</code>数据库中创建与之对应的表。</p>
<hr>
<p>2、构建rest api<br>
这里我们需要构建如下的rest api</p>
<table>
<thead>
<tr>
<th style="text-align:center">url</th>
<th style="text-align:left">method</th>
<th style="text-align:right">介绍</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>/user/</code></td>
<td style="text-align:left"><code>get</code></td>
<td style="text-align:right">获取所有的用户信息</td>
</tr>
<tr>
<td style="text-align:center"><code>/user/id/{id}</code></td>
<td style="text-align:left"><code>get</code></td>
<td style="text-align:right">根据id获取用户信息</td>
</tr>
<tr>
<td style="text-align:center"><code>/user/username/{username}</code></td>
<td style="text-align:left"><code>get</code></td>
<td style="text-align:right">根据username获取用户信息</td>
</tr>
<tr>
<td style="text-align:center"><code>/user</code></td>
<td style="text-align:left"><code>post</code></td>
<td style="text-align:right">新增用户信息</td>
</tr>
<tr>
<td style="text-align:center"><code>/user</code></td>
<td style="text-align:left"><code>put</code></td>
<td style="text-align:right">更新用户信息</td>
</tr>
<tr>
<td style="text-align:center"><code>/user/id/{id}</code></td>
<td style="text-align:left"><code>delete</code></td>
<td style="text-align:right">根据id删除用户信息</td>
</tr>
</tbody>
</table>
<p>那么这就是我们需要构建的<code>rest api</code>，那么对应的由<code>mvc</code>模式可知我们的<code>rest api</code>是<code>controller</code>层的，所以我们的<code>service</code>跟<code>repository</code>层(备注在使用 jpa的时候我们喜欢把dao层命名为repository)需要提供对应的接口。<br>
首先我们首先需要编写<code>UserRepository</code>接口，并且让它基础<code>JpaRepository</code>接口</p>
<p>新建包<code>repository</code> 创建<code>UserRepository.java</code>代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserRepository</span> <span class="keyword">extends</span> <span class="title">JpaRepository</span>&lt;<span class="title">User</span>, <span class="title">Long</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据用户名查找用户信息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> username</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">User <span class="title">findUserByUsername</span><span class="params">(String username)</span></span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>解释一下上面的代码，为什么只有一个方法，而前面我们是五个接口，因为是在JpaRepository中提供较为基础的增删改查方法，我们无需编写就看使用。如果大家不信按住<code>ctrl</code>点击JpaRepository看源码就知道了。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-062037.jpg" alt=""><br>
从上面就可以看出JpaRespository提供了哪些基础方法了。怎么样 是不是觉得很方便。那么接下来的第二点就Jpa可以根据你的命名规则来推断你这个方法作用，简单的来说<code>findUserByUsername</code> 根据这个方法名，jpa可以知道这个方法是通过用户名去查找用户。 具体的规则大家可以看<a href="https://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#jpa.query-methods" target="_blank" rel="noopener">文档</a><br>
<img src="http://cdn.yukonga.cn/2019-05-07-062003.jpg" alt=""><br>
如果大家用的idea的话，那么它会用智能提示功能，如图<br>
<img src="http://cdn.yukonga.cn/2019-05-07-062049.jpg" alt=""><br>
所以我们只需要编写方法名就可以轻轻松松的实现我们的查询方法，怎么样jpa是不是特别简单，但是需要注意的是方法名一定要命名规范，不要嫌太长了。<br>
接下来就是编写我们的service层了，<br>
新建<code>service</code>包创建<code>UserService.java</code>代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 添加用户信息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> user</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">User <span class="title">saveUser</span><span class="params">(User user)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新用户信息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> user</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">User <span class="title">updateUser</span><span class="params">(User user)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据id获取用户</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">User <span class="title">getById</span><span class="params">(Long id)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据名称获取用户</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> username</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">User <span class="title">getByUserName</span><span class="params">(String username)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查询所有用户</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">List&lt;User&gt; <span class="title">queryAll</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据id删除用户信息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">deleteById</span><span class="params">(Long id)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>接下里就下service的实现类，带service包下新建<code>impl</code>包并且创建实现类<code>UserServiceImpl.java</code> 代码如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserServiceImpl</span> <span class="keyword">implements</span> <span class="title">UserService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserRepository userRepository;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">saveUser</span><span class="params">(User user)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userRepository.save(user);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">updateUser</span><span class="params">(User user)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userRepository.save(user);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">getById</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userRepository.getOne(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">getByUserName</span><span class="params">(String username)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userRepository.findUserByUsername(username);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">queryAll</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userRepository.findAll();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteById</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">        userRepository.deleteById(id);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>那么紧接着就是控制层的代码了,新建<code>controller</code>包，并且创建<code>UserController.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(value = <span class="string">"/user"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserService userService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PostMapping</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">save</span><span class="params">(@RequestBody User user)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userService.saveUser(user);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PutMapping</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">update</span><span class="params">(@RequestBody User user)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userService.saveUser(user);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@DeleteMapping</span>(value = <span class="string">"/id/&#123;id&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">delete</span><span class="params">(@PathVariable  Long id)</span> </span>&#123;</span><br><span class="line">        userService.deleteById(id);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"删除成功"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(value = <span class="string">"/id/&#123;id&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">findById</span> <span class="params">(@PathVariable Long id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userService.getById(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(value = <span class="string">"/username/&#123;username&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">findByUsername</span> <span class="params">(@PathVariable String username)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userService.getByUserName(username);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(value = <span class="string">"/"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">findAll</span> <span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userService.queryAll();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样我们就完成了一个简单的<code>rest api</code>了啊。<br>
接下来我们来测试一下把。<br>
3、测试<br>
由于我们这里测试的是rest api普通的浏览器是没法支持 <code>post delet put</code>方式的访问的，所以这里我们就用<code>postman</code>来测试。<br>
1、首先我们看到test数据库中现在是一张表都没有的<br>
<img src="http://cdn.yukonga.cn/2019-05-07-062103.jpg" alt=""><br>
启动程序，注意观察日志。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-062116.jpg" alt=""></p>
<p>我们看到了日志打印了创建表的<code>ddl</code>那么我们再看看数据库中有没有表<br>
<img src="http://cdn.yukonga.cn/2019-05-07-062128.jpg" alt=""><br>
此时我们看到了有两张表，一张是我们user表，而另一张就是主键生成序列表。<br>
接下来就开始我们的<code>rest api</code>测试了。<br>
首先测试新增用户<br>
打开postman</p>
<p><img src="http://cdn.yukonga.cn/2019-05-07-062138.jpg" alt=""><br>
选择post模式，输入访问的url，然后选择body中的raw，因为我们使用的@RequestBody注解，所以我们选择raw中的Json，如图<br>
<img src="http://cdn.yukonga.cn/2019-05-07-062146.jpg" alt=""><br>
因为我们的id是自增的，所以我们不要输入，直接点击send访问，如果返回的数据有id那么就是代表新增成功。如下图就是新增成功。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-062154.jpg" alt=""><br>
打开数据库中的user表，看看数据有没有保存成功。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-062202.jpg" alt=""><br>
由图可知，保存成功。<br>
接下来我们就多添加几条数据。<br>
那么我们测试一下查询所有数据的方法。操作如图<br>
<img src="http://cdn.yukonga.cn/2019-05-07-062211.jpg" alt=""><br>
我们刚刚一共添加三条数据，全部都查询出来了。<br>
我们继续测试一下修改方法把。我们把id为2的数据密码修改为跟用户名一样，具体操作如图，<br>
<img src="http://cdn.yukonga.cn/2019-05-07-062219.jpg" alt=""><br>
点击send操作成功，我们用根据id查询的方法来查询一下刚刚id为2的数据有没有修改成功，那么我们查询一下id为2的数据，操作如图。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-062227.jpg" alt=""><br>
由图中可以看到我们的修改是成功的，用户名跟密码已经一样的，那么代表我们的根据id查询方法也是没问题的。那么另外几个方法我们不测试了，留给大家测试。</p>
<h1 id="三-总结"><a class="markdownIt-Anchor" href="#三-总结"></a> 三、总结</h1>
<p>这里我们通过这次选择对于jpa的使用有了一个初步的了解，并且对于rest api的规范也有了个了解。</p>
<p>最后配套教程的代码全部在这里<br>
<a href="https://github.com/YuKongEr/SpringBoot-Study" target="_blank" rel="noopener">github https://github.com/YuKongEr/SpringBoot-Study</a>。麻烦点个star或者fork吧。</p>
<p>欢迎大家关注一下我的个人公众号。一起交流一起学习，有问必答。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-055539.jpg" alt=""></p>

      
    </div>

    

    
    
    

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>喜欢就请博主喝个☕️吧</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="yukong 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="yukong 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>yukong</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="http://www.yukonga.cn/2018/08/17/【SpringBoot2-0系列04】SpringBoot之使用JPA完成简单的restapi/" title="【SpringBoot2.0系列04】SpringBoot之使用JPA完成简单的restapi">http://www.yukonga.cn/2018/08/17/【SpringBoot2-0系列04】SpringBoot之使用JPA完成简单的restapi/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    
    

      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/SpringBoot/" rel="tag"><i class="fa fa-tag"></i> SpringBoot</a>
          
            <a href="/tags/SpringDataJpa/" rel="tag"><i class="fa fa-tag"></i> SpringDataJpa</a>
          
            <a href="/tags/Rest/" rel="tag"><i class="fa fa-tag"></i> Rest</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/16/【SpringBoot2-0系列03】SpringBoot之使用freemark视图模板/" rel="next" title="【SpringBoot2.0系列03】SpringBoot之使用freemark视图模板">
                <i class="fa fa-chevron-left"></i> 【SpringBoot2.0系列03】SpringBoot之使用freemark视图模板
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/18/【SpringBoot2-0系列05】SpringBoot之整合Mybatis/" rel="prev" title="【SpringBoot2.0系列05】SpringBoot之整合Mybatis">
                【SpringBoot2.0系列05】SpringBoot之整合Mybatis <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.png" alt="yukong">
            
              <p class="site-author-name" itemprop="name">yukong</p>
              <div class="site-description motion-element" itemprop="description">你若对得起时间，时间便对得起你</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">26</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">6</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/YuKongEr" title="GitHub &rarr; https://github.com/YuKongEr" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:yukongcode@gmail.com" title="E-Mail &rarr; mailto:yukongcode@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.jianshu.com/u/bc2e35b66293" title="简书 &rarr; https://www.jianshu.com/u/bc2e35b66293" rel="noopener" target="_blank"><i class="fa fa-fw fa-skype"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://blog.csdn.net/xp541130126" title="csdn &rarr; https://blog.csdn.net/xp541130126" rel="noopener" target="_blank"><i class="fa fa-fw fa-vk"></i>csdn</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#一-前言"><span class="nav-number">1.</span> <span class="nav-text"> 一、前言</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#11-spring-data-jpa-介绍"><span class="nav-number">1.1.</span> <span class="nav-text"> 1.1、Spring Data Jpa 介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#22"><span class="nav-number">1.2.</span> <span class="nav-text"> 2.2</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二-目标"><span class="nav-number">2.</span> <span class="nav-text"> 二、目标</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#三-总结"><span class="nav-number">3.</span> <span class="nav-text"> 三、总结</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yukong</span>

  

  
</div>
<div class="BbeiAn-info">
浙ICP备 -
<a target="_blank" href="http://www.miitbeian.gov.cn">19015067号</a>

</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="post-meta-item-icon">
      <i class="fa fa-user"></i>
      您是访问本站的第&nbsp
    </span>
    <span class="site-uv" title="总访客量">
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      &nbsp 位朋友
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="post-meta-item-icon">
      <i class="fa fa-eye"></i>
      本站总共访问&nbsp
    </span>
    <span class="site-pv" title="总访问量">
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>









        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.1"></script>

  <script src="/js/src/motion.js?v=7.0.1"></script>



  
  


  <script src="/js/src/affix.js?v=7.0.1"></script>

  <script src="/js/src/schemes/pisces.js?v=7.0.1"></script>




  
  <script src="/js/src/scrollspy.js?v=7.0.1"></script>
<script src="/js/src/post-details.js?v=7.0.1"></script>



  


  <script src="/js/src/next-boot.js?v=7.0.1"></script>


  

  

  

  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
    appKey: 'n3ohmj1CGAM1GUfp6SqF4LXh',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: 'zh-cn' || 'zh-cn'
  });
</script>




  


  




  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
                'X-LC-Key': 'n3ohmj1CGAM1GUfp6SqF4LXh',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  

  

  

  

  

  

  

  

  

  
<script>
  $('.highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
